package cn.bitkit.tools.common;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 仅用于单机环境
 * @author changbo
 */
public class SimpleLock<T> {

    private final ConcurrentHashMap<T, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    public boolean tryLock(T id) {
        // computeIfAbsent是原子操作，确保每个id对应的锁只创建一次
        ReentrantLock lock = lockMap.computeIfAbsent(id, k -> new ReentrantLock());
        return lock.tryLock();
    }

    public void unlock(T id) {
        ReentrantLock lock = lockMap.get(id);
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
            // 可选：如果锁不再被持有，可以从map中移除以节省内存
            if (!lock.isLocked()) {
                lockMap.remove(id, lock);
            }
        }
    }
}
